﻿using WPFServices.Models;
using WPFServices.Models.Domain;

namespace WPFServices.Services.DomainService.Role
{
    public class RoleService
    {
        private readonly ApiClient _apiClient;

        public RoleService()
        {
            _apiClient = new ApiClient();
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        public async Task<RoleDto> CreateRoleAsync(CreateUpdateRoleDto role)
        {
            var result = await _apiClient.PostAsync<RoleDto>("Role/AddRole", role);

            if (result.IsSuc && result.code == ResultCode.Ok)
            {
                return result.data;
            }
            else
            {
                throw new Exception($"创建角色失败: {result.msg}");
            }
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        public async Task<RoleDto> UpdateRoleAsync(int id, CreateUpdateRoleDto role)
        {
            var result = await _apiClient.PutAsync<RoleDto>($"Role/UpdateRole?roleid={id}", role);

            if (result.IsSuc && result.code == ResultCode.Ok)
            {
                return result.data;
            }
            else
            {
                throw new Exception($"更新角色失败: {result.msg}");
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        public async Task<bool> DeleteRoleAsync(int id)
        {
            var result = await _apiClient.DeleteAsync($"Role/DeleteRole?roleId={id}");

            if (result.IsSuc && result.code == ResultCode.Ok)
            {
                return true;
            }
            else
            {
                throw new Exception($"删除角色失败: {result.msg}");
            }
        }

        /// <summary>
        /// 分页查询角色
        /// </summary>
        public async Task<ApiPaging<List<RoleDto>>> SearchRolesAsync(SearchRoleDto searchDto)
        {
            var queryParams = $"PageIndex={searchDto.PageIndex}&PageSize={searchDto.PageSize}";
            if (!string.IsNullOrEmpty(searchDto.RoleName))
            {
                queryParams += $"&RoleName={Uri.EscapeDataString(searchDto.RoleName)}";
            }

            var result = await _apiClient.GetAsync<ApiPaging<List<RoleDto>>>($"Role/GetAllRoles?{queryParams}");

            if (result.IsSuc && result.code == ResultCode.Ok)
            {
                return result.data;
            }
            else
            {
                throw new Exception($"查询角色失败: {result.msg}");
            }
        }
    }
}